package com.pureut.production.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.domain.CutOrdersDocumentDetail;
import com.pureut.production.domain.SpunlaceOutputDetail;
import com.pureut.production.domain.dto.SpunlaceOutputDetailDto;
import com.pureut.production.domain.dto.SpunlaceOutputViewDto;
import com.pureut.production.domain.vo.SpunlaceOutputDetailVo;
import com.pureut.production.domain.vo.UpdateProductionCheckVo;
import com.pureut.production.mapper.CutOrdersDocumentDetailMapper;
import com.pureut.production.mapper.SpunlaceOutputDetailMapper;
import com.pureut.production.service.CutOrdersDocumentDetailService;
import com.pureut.production.service.SpunlaceOutputDetailService;
import com.pureut.system.api.StorageFegin;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.UpdateGradeVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: CM
 * @date: 2023/2/20  17:01
 */
@Service
public class SpunlaceOutputDetailServiceImpl extends ServiceImpl<SpunlaceOutputDetailMapper, SpunlaceOutputDetail> implements SpunlaceOutputDetailService {

    @Resource
    private SpunlaceOutputDetailMapper spunlaceOutputDetailMapper;

    /**
     * 仓储Fegin
     */
    @Resource
    private StorageFegin storageFegin;

    @Resource
    private CutOrdersDocumentDetailMapper cutOrdersDocumentDetailMapper;

    @Resource
    private CutOrdersDocumentDetailService cutOrdersDocumentDetailService;

    /**
     * 水刺产出明细新增
     * @param spunlaceOutputDetailVo
     * @return
     */
    @Override
    public boolean add(SpunlaceOutputDetailVo spunlaceOutputDetailVo) {
        SpunlaceOutputDetail spunlaceOutputDetail = new SpunlaceOutputDetail();
        BeanUtils.copyProperties(spunlaceOutputDetailVo,spunlaceOutputDetail);
        spunlaceOutputDetail.setCreateTime(new Date());
        spunlaceOutputDetail.setCreateMan(SecurityUtils.getUsername());
        return save(spunlaceOutputDetail);
    }

    /**
     * 水刺产出明细列表
     * @param moNumber
     * @return
     */
    @Override
    public List<SpunlaceOutputDetailDto> getList(String moNumber) {
        List<SpunlaceOutputDetailDto> spunlaceOutputDetailDtoList=spunlaceOutputDetailMapper.selectDetail(moNumber);

        for (SpunlaceOutputDetailDto spunlaceOutputDetailDto : spunlaceOutputDetailDtoList) {
            //物料等级
            List<SysDictData> gradeArray = DictUtils.getDictCache("spunlace_item_grade");
            Map<String, String> gradeMap = gradeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            //检验单结果
            List<SysDictData> resultArray = DictUtils.getDictCache("check_result");
            Map<String, String> resultMap = resultArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            //检验单状态
            List<SysDictData> checkArray = DictUtils.getDictCache("check_status");
            Map<String, String> checkMap = checkArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            //生产状态
            List<SysDictData> statusArray = DictUtils.getDictCache("spunlace_output_detail_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            //生产状态
            List<SysDictData> classArray = DictUtils.getDictCache("scheduling_class_info");
            Map<String, String> classMap = classArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            spunlaceOutputDetailDto.setProductionStatusDict(statusMap.get(spunlaceOutputDetailDto.getProductionStatus()));//生产状态
            spunlaceOutputDetailDto.setMaterielGradeDict(gradeMap.get(spunlaceOutputDetailDto.getMaterielGrade()));//物料等级
            spunlaceOutputDetailDto.setCheckStatusDict(checkMap.get(spunlaceOutputDetailDto.getCheckStatus()));//检验单状态
            spunlaceOutputDetailDto.setCheckResultDict(resultMap.get(spunlaceOutputDetailDto.getCheckResult()));//检验单结果
            spunlaceOutputDetailDto.setClasses(classMap.get(spunlaceOutputDetailDto.getClasses()));

        }
        return spunlaceOutputDetailDtoList;

    }

    /**
     * 补打
     * @param ids
     * @return
     */
    @Override
    public List<SpunlaceOutputDetailDto> reprint(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<SpunlaceOutputDetailDto> spunlaceOutputDetailDto = spunlaceOutputDetailMapper.selectReprint(idList);

        return spunlaceOutputDetailDto;
    }

    /**
     * 条码修正
     * @param spunlaceOutputDetailVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(SpunlaceOutputDetailVo spunlaceOutputDetailVo) {

        //修改当前单据的信息
        SpunlaceOutputDetail spunlaceOutputDetail = spunlaceOutputDetailMapper.selectById(spunlaceOutputDetailVo.getId());

        if (!"1".equals(spunlaceOutputDetail.getProductionStatus())){
            throw new GlobalException("只能对待入库的单据进行修正");
        }

        spunlaceOutputDetail.setGrossWeight(spunlaceOutputDetailVo.getGrossWeight());//毛重
        spunlaceOutputDetail.setNetWeight(spunlaceOutputDetailVo.getNetWeight());//净重
        spunlaceOutputDetail.setRollLength(spunlaceOutputDetailVo.getRollLength());//卷长
        spunlaceOutputDetail.setRollingDiameter(spunlaceOutputDetailVo.getRollingDiameter());//卷径
        spunlaceOutputDetail.setBreadth(spunlaceOutputDetailVo.getBreadth());//幅宽
        spunlaceOutputDetail.setGrawWeight(spunlaceOutputDetailVo.getGrawWeight());//克重
        spunlaceOutputDetail.setThick(spunlaceOutputDetailVo.getThick());//厚度
        spunlaceOutputDetail.setJoint(spunlaceOutputDetailVo.getJoint());//接头
        spunlaceOutputDetail.setExceptionRemark(spunlaceOutputDetailVo.getExceptionRemark());//异常备注
        spunlaceOutputDetail.setDefect(spunlaceOutputDetailVo.getDefect());//疵点

        int i = spunlaceOutputDetailMapper.updateById(spunlaceOutputDetail);

        //修改库存信息
        return i>0;
    }

    /**
     * 条码修正回显
     * @param id
     * @return
     */
    @Override
    public SpunlaceOutputViewDto editView(Long id) {
        return spunlaceOutputDetailMapper.editView(id);

    }


    /**
     * 根据物料号码获取明细数据(fegin调用)
     * @param materialNumber
     * @return
     */
    @Override
    public SpunlaceOutputDetailDto getSpunlaceDetail(String materialNumber) {

        return spunlaceOutputDetailMapper.getSpunlaceDetail(materialNumber);
    }

    /**
     * 根据制令单号获取明细数据(fegin调用)
     * @param orderNum
     * @return
     */
    @Override
    public List<SpunlaceOutputDetailDto> getDetailList(String orderNum) {
        return spunlaceOutputDetailMapper.getDetailList(orderNum);
    }

    /**
     * 根据品质检验结果修改水刺产出明细状态
     * @param updateProductionCheckVo
     * @return
     */
    @Override
    public boolean spunlaceUpdateStatus(UpdateProductionCheckVo updateProductionCheckVo) {

        //获取审核状态，检验结果
        String type = updateProductionCheckVo.getType();
        String result = updateProductionCheckVo.getResult();
        String docNum = updateProductionCheckVo.getDocNum();
        String qualityDoc = updateProductionCheckVo.getQualityDoc();
        String qualityStatus = updateProductionCheckVo.getQualityStatus();//检验状态





        //修改仓库的物料等级
        //母卷号码集合
        List<String> materialNumberList = new ArrayList<>();

        List<CutOrdersDocumentDetail> cutOrdersDocumentDetailList = new ArrayList<>();


        //如果首检通过
        if ("1".equals(type) && "1".equals(result)){

            List<SpunlaceOutputDetail> spunlaceOutputDetailList11 = spunlaceOutputDetailMapper.selectList(new QueryWrapper<SpunlaceOutputDetail>().lambda().eq(SpunlaceOutputDetail::getSpunlaceOrderNumber, docNum).eq(SpunlaceOutputDetail::getConnectQualityDoc, qualityDoc));

            //修改号码检验单状态为“检验完成：，检验结果为“合格”，物料等级为“良品”
            for (SpunlaceOutputDetail spunlaceOutputDetail : spunlaceOutputDetailList11) {
                spunlaceOutputDetail.setCheckStatus("2");//检验完成
                spunlaceOutputDetail.setCheckResult("1");//合格
                spunlaceOutputDetail.setMaterielGrade("1");//良品

                //查询分切明细对应母卷的条码
                CutOrdersDocumentDetail cutOrdersDocumentDetail = cutOrdersDocumentDetailMapper.selectOne(new QueryWrapper<CutOrdersDocumentDetail>().lambda().eq(CutOrdersDocumentDetail::getProductNumber, spunlaceOutputDetail.getProductionNumber()));

                //如果没有分切单
                if (cutOrdersDocumentDetail!=null){
                    cutOrdersDocumentDetail.setMaterialLevel(1);
                    cutOrdersDocumentDetailList.add(cutOrdersDocumentDetail);
                }


                materialNumberList.add(spunlaceOutputDetail.getProductionNumber());
            }
            boolean b = updateBatchById(spunlaceOutputDetailList11);

            if (b) {
                //查询物料等级为null的母卷号码
                List<SpunlaceOutputDetail> spunlaceOutputDetailList = spunlaceOutputDetailMapper.selectIsNullGrade(docNum);

                List<SpunlaceOutputDetail> newList = new ArrayList<>();

                for (SpunlaceOutputDetail spunlaceOutputDetail : spunlaceOutputDetailList) {
                    spunlaceOutputDetail.setMaterielGrade("1");//良品
                    newList.add(spunlaceOutputDetail);
                }
                updateBatchById(newList);
            }


        }else if ("2".equals(type)&&"6".equals(qualityStatus) && "2".equals(result)){ //如果是待处理，且结果是不合格，不通过
            List<SpunlaceOutputDetail> spunlaceOutputDetailList11 = spunlaceOutputDetailMapper.selectList(new QueryWrapper<SpunlaceOutputDetail>().lambda().eq(SpunlaceOutputDetail::getSpunlaceOrderNumber, docNum).eq(SpunlaceOutputDetail::getConnectQualityDoc, qualityDoc));
            //修改号码检验状态为”检验完成“
            for (SpunlaceOutputDetail spunlaceOutputDetail : spunlaceOutputDetailList11) {
                spunlaceOutputDetail.setCheckStatus("2");//检验完成
                spunlaceOutputDetail.setCheckResult("2");//不合格

            }

            boolean b = updateBatchById(spunlaceOutputDetailList11);
        }

        //修改分切的物料等级
        boolean b = cutOrdersDocumentDetailService.updateBatchById(cutOrdersDocumentDetailList);

        if (b){
            //修改仓库的物料等级
            UpdateGradeVo updateGradeVo = new UpdateGradeVo();
            updateGradeVo.setMaterialNumberList(materialNumberList);
            updateGradeVo.setMaterialLevel(1);
            storageFegin.updateMaterialGrade(updateGradeVo);
        }

        return b;
    }

    /**
     * 品质处理回传物料等级
     * @param updateProductionCheckVo
     * @return
     */
    @Override
    public boolean spunlaceUpdateGrade(UpdateProductionCheckVo updateProductionCheckVo) {
        String grade = updateProductionCheckVo.getGrade();
        String docNum = updateProductionCheckVo.getDocNum();
        String qualityDoc = updateProductionCheckVo.getQualityDoc();

        List<SpunlaceOutputDetail> spunlaceOutputDetailList = spunlaceOutputDetailMapper.selectList(new QueryWrapper<SpunlaceOutputDetail>().lambda().eq(SpunlaceOutputDetail::getSpunlaceOrderNumber, docNum).eq(SpunlaceOutputDetail::getConnectQualityDoc, qualityDoc));

        List<CutOrdersDocumentDetail> cutOrdersDocumentDetailList = new ArrayList<>();

        //母卷号码集合
        List<String> materialNumberList = new ArrayList<>();

        //修改号码检验状态为”检验完成“
        for (SpunlaceOutputDetail spunlaceOutputDetail : spunlaceOutputDetailList) {

            //品质:3:返工，4:报废
            //2:报废，3：返工
            if ("4".equals(grade)){
                grade="2";
            }
            spunlaceOutputDetail.setMaterielGrade(grade);//物料等级

            //查询分切明细对应母卷的条码
            CutOrdersDocumentDetail cutOrdersDocumentDetail = cutOrdersDocumentDetailMapper.selectOne(new QueryWrapper<CutOrdersDocumentDetail>().lambda().eq(CutOrdersDocumentDetail::getProductNumber, spunlaceOutputDetail.getProductionNumber()));

            cutOrdersDocumentDetail.setMaterialLevel(Integer.parseInt(grade));
            cutOrdersDocumentDetailList.add(cutOrdersDocumentDetail);

            materialNumberList.add(spunlaceOutputDetail.getProductionNumber());

        }
        boolean b = cutOrdersDocumentDetailService.updateBatchById(cutOrdersDocumentDetailList);

        if (b){
            UpdateGradeVo updateGradeVo = new UpdateGradeVo();
            updateGradeVo.setMaterialNumberList(materialNumberList);
            updateGradeVo.setMaterialLevel(Integer.parseInt(updateProductionCheckVo.getGrade()));
            storageFegin.updateMaterialGrade(updateGradeVo);
        }
        return updateBatchById(spunlaceOutputDetailList);
    }

    /**
     * 根据母卷号码查询详情(产品追溯feign)
     * @param productionNumber
     * @return
     */
    @Override
    public SpunlaceOutputDetailDto selectSpunlaceDetailList(String productionNumber) {
        return spunlaceOutputDetailMapper.selectSpunlaceDetailList(productionNumber);
    }


}
